<?php
	include_once("connect.php");
	mysql_select_db("progin_171_13509047",$con);
	session_start();
	
	include_once("tag_model.php");
	include_once("post_model.php");
	include_once("search_model.php");
	include_once("do_listing.php");
	include_once("header.php");
?>

<div id="bodycontent">
	<div class="contentcontainer">
	<?php
		$input = $_GET["q"];
		$opt = $_GET["search_type"];
		
		global $pil; 
		if($opt == "all") {
			$pil = 1;
		} else if($opt == "username") {
			$pil = 2;
		} else if($opt == "content") {
			$pil = 3;
		}
	
		$ufound = false;
		$cfound = false;
		
		if($pil == 1 || $pil == 2) {
			echo "<div class='contentbox'>";
			echo "<div class='title-text'>";
			echo "<h1>Username search result</h1>";
			echo "</div>";
			
			$sm = new Search_Model();
			$res = $sm->searchUsername($input);
			
			echo "<ul>";
			while($row = mysql_fetch_array($res)) {
				$ufound = true;
				echo "<li>";
				$out = "<a href=profile.php?id=$row[ID]>$row[username]</a>";
				echo $out;
				echo "</li>";
			}
			
			if(!$ufound) {
				echo "No result found";
			}
			
			echo "</ul>";
			echo "</div>";
		}
		
		if($pil == 1 || $pil == 3) {
			echo "<div class='contentbox'>";
			echo "<div class='title-text'>";
			echo "<h1>Content search result</h1>";
			echo "</div>";
			
			//simpen ID post yang dicari
			$resid = array();
			$sm = new Search_Model();
			$pm = new Post_Model();
			$tm = new Tag_Model();
			
			$res_con = $sm->searchContent($input);
			$res_tag = $sm->searchTag($input);
		
			while($row = mysql_fetch_array($res_con)) {
				$resid[] = $row["ID"];
			}
			
			while($row = mysql_fetch_array($res_tag)) {
				$resid[] = $row["post_id"];
			}
			
			$resid = array_unique($resid);
			
			echo "<ul>";
			foreach($resid as $id) {
				$res = $pm->getPost($id);
				while($row = mysql_fetch_array($res)) {
					$cfound = true;
					echo "<li>";
					echo "<a href='content.php?id=$id'>$row[title]</a>";
					echo "<br />";
					$desc = explode("\n", $row["content"]);
					echo "$desc[0]";
					if(isset($desc[1])) {
						echo "<br />$desc[1]";
					}
					echo "<br />";
					
					echo "Tags: ";
					$restag = $tm->getTags($id);
					while($rowtag = mysql_fetch_array($restag)) {
						echo $rowtag["type"];
						echo "&nbsp;";
					}
					
					echo "</li>";
				}
			}
			
			if(!$cfound) {
				echo "No result found";
			}
			
			echo "</ul>";
			echo "</div>";
		}
	?>
	</div>
</div>

<?php
	include_once("footer.php");
?>